package com.gopay.common.event;

import java.util.LinkedHashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.NoTransactionException;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.Assert;

import com.gopay.common.domain.report.Event;
import com.gopay.common.event.store.EventStorage;


/**
 * 事件收集器
 */
@Service(value = "eventCollector")
public class EventCollector extends TransactionSynchronizationAdapter {
    
    private final static Logger logger = LoggerFactory.getLogger(EventCollector.class);
	
	private final static ThreadLocal<Set<Event>> tlSet = new ThreadLocal<Set<Event>>();
	
	@Override
	public void afterCompletion(int status) {
	    try{	        
    		if(STATUS_COMMITTED == status){
    			Set<Event> set = tlSet.get();
    			if(set != null){
    			    new EventStorage().store(set);
    			}
    		}
    		
    		tlSet.remove();		
	    }catch(Exception e){
	      //吃掉所有异常
	      logger.error("EventCollector.afterCompletion Error", e);
	    }
	}
	
	public void start(){
		if(TransactionSynchronizationManager.isSynchronizationActive()){
			TransactionSynchronizationManager.registerSynchronization(this);
		} else {
			throw new NoTransactionException("当前线程没有活动的同步事务！");
		}
	}

	public void collect(Event event){
		Assert.notNull(event, "Event must not be null");
		Set<Event> set = tlSet.get();
		if(set == null){
			set = new LinkedHashSet<Event>();
		}
		set.add(event);
		
		tlSet.set(set);
	}
	
	public void collect(Set<Event> events){
		Assert.notEmpty(events, "Events must not be empty");
		Set<Event> set = tlSet.get();
		if(set == null){
			set = new LinkedHashSet<Event>();
		}
		set.addAll(events);
		
		tlSet.set(set);
	}
}
